import {
	http
} from '@/utils/commonRequest_helper.js'; // 局部引入
import promise from '@/utils/promise.js'
import {
	MAX_INACTIVE_INTERVAL
} from '@/utils/constant.js'

let app = getApp()
// #ifdef MP-WEIXIN
let saveCsrfToken = function(header) {
	var cookie_str;
	for (var key in header) {
		if ('set-cookie' == key.toLowerCase()) {
			cookie_str = header[key];
			break;
		}
	}
	if (null == cookie_str || undefined == cookie_str) {
		return;
	}
	var start = cookie_str.indexOf('csrf_token');
	var end;
	var csrfTokenT;

	while (start > -1) {
		end = cookie_str.indexOf(';', start);
		if (end == -1) {
			end = cookie_str.length;
		}
		csrfTokenT = cookie_str.substring(start + 'csrf_token'.length + 1, end);
		if (null != csrfTokenT && 'null' != csrfTokenT && '' != csrfTokenT && undefined != csrfTokenT) {
			wx.setStorageSync("LOGIN_CSRFTOKEN_HELPER", csrfTokenT);
			console.log('CSRF ' + wx.getStorageSync("LOGIN_CSRFTOKEN_HELPER"));
			return;
		}
		start = cookie_str.indexOf('csrf_token', end);
	}
}
/**
 * 登录
 */
let login = function() {
	wx.setStorageSync("LOGIN_HELPER", "expire");
	wx.removeStorageSync("LOGIN_LASTTIME_HELPER");
	wx.removeStorageSync("LOGIN_JSESSIONID_HELPER");
	wx.removeStorageSync("LOGIN_CSRFTOKEN_HELPER");
	let that = getApp()
	let info = uni.getStorageSync('memberInfo_helper')
	return new Promise((resolve, reject) => {
		wx.login({
			success: res => {
				let code = res.code;
				wx.request({
					url: that.globalData.baseurl + '/mtBankInfo/mtloginNotAuthPlat',
					data: {
						code: code,
						appid: that.globalData.appid,
						usn: info.usn
					},
					success: res => {
						console.log(res);
						if (res.data.login == "login" || res.data.login ==
							"authed" || res.data.login == "success") {

							wx.setStorageSync("LOGIN_HELPER", res.data.login);
							wx.setStorageSync("LOGIN_LASTTIME_HELPER", new Date());
							wx.setStorageSync("LOGIN_JSESSIONID_HELPER", res.data
								.JSESSIONID);
							uni.setStorageSync('memberInfo_helper', res.data
								.memberInfo)

							that.globalData.memberInfo_helper = (res.data.login ==
								"authed") ? res.data.memberInfo : null;
							that.globalData.platId = (res.data.login == "authed") ?
								res.data.platId : null
							that.globalData.defaultCity = '吉林省'
							that.globalData.locatedCity = '吉林省'
							uni.setStorageSync("platType_helper", res.data.platType)
							that.globalData.platType = res.data.platType;
							saveCsrfToken(res.header);
							resolve(res.data.login);
						} else {
							reject("failed");
						}
					},
					fail: (err) => {
						console.log(err);
						reject("failed");
					}
				})
			},
			fail: function(err) {
				console.log(err);
				reject("failed");
			}
		})
	});
}

/**
 * 检查登录
 */
let checkLogin = function() {
	let app = getApp()
	let that = this;
	return new promise((resolve, reject) => {

		var logins = wx.getStorageSync("LOGIN_HELPER");
		var lastTime = wx.getStorageSync("LOGIN_LASTTIME_HELPER");

		if (typeof lastTime == "object") {
			lastTime = lastTime.getTime();
		};
		console.log(app, '执行登录11')
		console.log('执行登录222', logins)
		if (("login" == logins || "authed" == logins || "success" == logins) && ((new Date()).getTime() -
				lastTime) < (app.globalData.MAX_INACTIVE_INTERVAL - 30) * 1000) {
			console.log('执行登录1')
			resolve(logins);
		} else {
			//登录超时,重新登录
			console.log('执行登录2')
			login().then(res => resolve(res)).catch(err => reject(err));
		}
	});
}


let checkAuth_helper2 = function() {	
	let app = getApp()
	let that = this;

	let lastAuthTime = uni.getStorageSync("AUTH_LASTTIME_HELPER");
	if (typeof lastAuthTime == "object") {
		lastAuthTime = lastAuthTime.getTime();
	}
	let sessionMemberInfo_helper = uni.getStorageSync('memberInfo_helper')

	let url = '/subPackages/helper/pages/regist/phoneVerify';
	let urlIndex = '/subPackages/helper/pages/index/index'
	let pages = getCurrentPages(); //页面对象
	let prevpage = pages[pages.length - 2]; //上一个页面对象
	console.log(prevpage.route) //上一个页面路由地址

	return new Promise((resolve, reject) => {
		uni.removeStorageSync("AUTH_LASTTIME_HELPER")
		uni.removeStorageSync('memberInfo_helper')

		http.get('/mtBankInfo/checkAuth', {})
			.then(res => {
				if (200 == res.data.code) {
					if (res.data.mtStaffDto) {
						uni.setStorageSync("AUTH_LASTTIME_HELPER", new Date()); //上次登录时间
						let memberInfo = res.data.mtStaffDto
						uni.setStorageSync('memberInfo_helper', memberInfo)
						//从积分商城点进来才如果已登录则跳转首页
						if(prevpage.route == 'pages/my/my') {
							wx.redirectTo({
								url: urlIndex
							})
						}
						resolve(res)
					} else {
						uni.hideLoading();
						wx.redirectTo({
							url: url
						})
						wx.removeStorageSync('LOGIN_JSESSIONID_HELPER')
						reject("failded")
					}
				} else {
					wx.redirectTo({
						url: url
					})
					reject("failded")
				}
			})
			.catch(err => {
				console.log(err);
				reject("failded")
			});
	})
}


// #endif
// #ifdef H5 || MP-UNIONPAY


let checkLogin = function() {
	let that = this
	let lastTime = uni.getStorageSync("LOGIN_LASTTIME_HELPER");
	if (typeof lastTime == "object") {
		lastTime = lastTime.getTime();
	}
	return new Promise((resolve, reject) => {
		if (((new Date()).getTime() - lastTime) < (MAX_INACTIVE_INTERVAL - 30) * 1000) {
			resolve()
			return
		}
		http.get('/auth/checkLogin', {})
			.then(res => {
				if (200 == res.data.code) {
					uni.setStorageSync("LOGIN_LASTTIME_HELPER", new Date());
					uni.setStorageSync("platType_helper", res.data.platType)
					resolve()
				} else {
					reject("failded")
				}
			})
			.catch(err => {
				console.log(err);
				reject("failded")
			});
	})
}

// #endif

module.exports = {
	checkLogin_helper: checkLogin,
	checkAuth_helper: checkAuth_helper2
}